package rssgate;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import rssgate.dao.PMF;
import rssgate.dao.entity.RSSImage;
import rssgate.dao.entity.RSSItem;
import rssgate.util.LogUtils;

@SuppressWarnings("serial")
public class CleanerServiceServlet extends HttpServlet{
	private static final Logger log = Logger.getLogger(InstallServiceServlet.class
			.getName());
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		final PersistenceManager pm = PMF.get().getPersistenceManager();		
		// clear all DB
		String msg = "INFO: Start Cleaning";
		final PrintWriter writer = resp.getWriter();
		LogUtils.logMsg(log, msg,writer);
				
		final Date last2Remove = ConstUtils.getLast2Remove();
	
		msg = "INFO: Delete all rows from " + RSSImage.class.getName() + " where modified < last2Remove range 0,10";
		LogUtils.logMsg(log, msg,writer);		
		Query newQuery2 = pm.newQuery("select from " + RSSImage.class.getName() + " where modified < last2Remove range 0,10");
		newQuery2.declareParameters("java.util.Date last2Remove");
		final List<RSSImage> items = (List<RSSImage>) pm.newQuery(newQuery2).execute(last2Remove);				
		pm.deletePersistentAll((Collection) items);

		msg = "INFO: Delete all rows from " + RSSItem.class.getName() +  " where storedData < last2Remove range 0,10";
		LogUtils.logMsg(log, msg,writer);		
		Query newQuery3 = pm.newQuery("select from " + RSSItem.class.getName() + " where storedData < last2Remove range 0,10");
		newQuery3.declareParameters("java.util.Date last2Remove");
		Object execute3 = newQuery3.execute(last2Remove);
		pm.deletePersistentAll((Collection) execute3);
	}
}
